from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from checkin.models import Event
from django.contrib.auth.models import User
from datetime import datetime
from datetime import timedelta
from django.template import RequestContext
from social.views import getUsageProfile
import math
import csv

ANALYTICS_TYPES = [('Overview',''), ('Hourly Usage','hourly'), ('Daily Usage','daily'), ('Historical Usage','historical')]

class Data:
	headings = []
	points = []


def getUsage():
	return Event.objects.filter(timestamp__gte=datetime.now()-timedelta(hours=1), eventType='I').count()


def getHeatmap(user=None):
	users = User.objects.filter()
	if(user):
		users = users.filter(pk=user.pk)
	usages = []
	
	#Collect usages for all users
	for user in users:
		usages.append(getUsageProfile(user))
	
	usageMap = []
	
	for i in range(168):
		#Average all user usages
		totalUsage = 0.0
		numUsages = 0
		for usage in usages:
			totalUsage += usage[i]
			numUsages += 1
		avgUsage = totalUsage / numUsages
		usageMap.append((i, avgUsage))
	
	#Normalize usageMap
	maxUsage = max(usageMap, key=lambda x: x[1])
	for key,value in usageMap:
		if not maxUsage[1] == 0.0:
			usageMap[key] = (key, value / maxUsage[1])
		else:
			usageMap[key] = (key, 0.0)
	
	return usageMap


def exportToCSV(data):
	response = HttpResponse(mimetype="text/csv")
	response["Content-Disposition"] = "attachment; filename=export.csv"
	writer = csv.writer(response)
	writer.writerow(data.headings)
	writer.writerow(data.points)
	return response


def analytics(request):
	return render_to_response("analytics/analytics.html", {'usageMap':getHeatmap(user=request.user), 'types':ANALYTICS_TYPES, 'type':''}, context_instance=RequestContext(request))


def overview(request):
	return render_to_response("analytics/analytics.html", {'compareMap':getHeatmap(), 'types':ANALYTICS_TYPES, 'type':''}, context_instance=RequestContext(request))


def current_processor(request):
	return {'currentUsage':getUsage()}


def hourly(request):
	hours = ['AM', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', 'PM', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11']
	hourPoints = []
	
	start = int(request.GET.get('start', 30))
	end = int(request.GET.get('end', 0))
	events = Event.objects.filter(eventType='I', timestamp__lt = datetime.now() - timedelta(days=end), timestamp__gte = datetime.now() - timedelta(days=start))
	
	startList = [(1, 'Last Day'), (7, 'Last Week'), (30, 'Last Month'), (365, 'Last Year')]
	
	eventHours = [0]*24
	for event in events:
		eventHours[event.timestamp.hour] = eventHours[event.timestamp.hour] + 1
	
	for i in range(24):
		hourPoints.append((hours[i], eventHours[i]))
	
	data = Data()
	data.headings = []
	data.points = []
	for hour, point in hourPoints:
		data.headings.append(hour)
		data.points.append(point)
	
	if(request.GET.get('export')):
		return exportToCSV(data)
	
	return render_to_response("analytics/analytics.html", {'types':ANALYTICS_TYPES, 'type':'hourly', 'data':data, 'chartType':'line', 'start':start, 'end':end, 'startList':startList}, context_instance=RequestContext(request))


def daily(request):
	days = ['Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
	
	start = int(request.GET.get('start', 30))
	end = int(request.GET.get('end', 0))
	dayPoints = []
	for i in range(7):
		dayPoints.append((days[i], Event.objects.filter(timestamp__week_day=i, eventType='I', timestamp__lt = datetime.now() - timedelta(days=end), timestamp__gte = datetime.now() - timedelta(days=start)).count()))
	
	startList = [(7, 'Last Week'), (30, 'Last Month'), (365, 'Last Year')]
	
	data = Data()
	data.headings = []
	data.points = []
	for day, point in dayPoints:
		data.headings.append(day)
		data.points.append(point)
	
	if(request.GET.get('export')):
		return exportToCSV(data)
	
	return render_to_response("analytics/analytics.html", {'types':ANALYTICS_TYPES, 'type':'daily', 'data':data, 'start':start, 'end':end, 'startList':startList}, context_instance=RequestContext(request))


def historical(request):
	start = int(request.GET.get('start', 30))
	end = int(request.GET.get('end', 0))
	
	dayPoints = []
	labelEvery = int(math.ceil(start / 10.0))
	for i in range(start + 1):
		endTime = datetime.now() - timedelta(days=i)
		startTime = endTime - timedelta(days=1)
		totalEvents = Event.objects.filter(timestamp__gte = startTime, timestamp__lt = endTime).count()
		label = ""
		if i % labelEvery == 0:
			daysAgo = i
			thatDay = datetime.now() - timedelta(days = daysAgo)
			label = str(thatDay.month) + "/" + str(thatDay.day)
		dayPoints.append((label, totalEvents))
	
	dayPoints.reverse();
	
	startList = [(7, 'Last Week'), (30, 'Last Month'), (365, 'Last Year')]
	
	data = Data()
	data.headings = []
	data.points = []
	for day, point in dayPoints:
		data.headings.append(day)
		data.points.append(point)
	
	if(request.GET.get('export')):
		return exportToCSV(data)
	
	return render_to_response("analytics/analytics.html", {'types':ANALYTICS_TYPES, 'type':'historical', 'start':start, 'end':end, 'startList':startList, 'data':data, 'chartType':'line'}, context_instance=RequestContext(request))


